<?php
namespace controllers\admin;
use controllers\AdminApi;
/**
 * Class index
 * @package controllers\admin
 * @auth    配置管理
 */
class SiteConfig extends AdminApi{
	/**
	 * 初始化
	 */
	public function onStepUp(){
		$this->model = new \models\Config();
	}

	/**
	 * @auth 配置列表
	 * @param string $title
	 * @author Colin <amcolin@126.com>
	 * @date 2021-12-20 下午3:51
	 * @return array
	 */
	public function index($title = ''){
		$map = [];
		if ($title){
			$map['a.title like'] = $title;
		}
		$list = $this->model->alias('a')->where($map)->select();
		foreach ($list as &$val){
			$val['type'] = $this->model::TypesFormat[$val['type']];
		}
		return self::returnJson($list);
	}

	public function onUpdateBefore(&$data = []) {
		if (self::$post['id']) {
			$find = $this->model->getFind(self::$post['id']);
			if (!$find) {
				$this->error = '信息不存在';
				return false;
			}
		}
		$find = $this->model->where(['name' => self::$post['name']])->field('id,value')->find();
		if ($find && $find['id'] != self::$post['id']) {
			$this->error = '此配置已存在';
			return false;
		}
		if ($data['type'] == 3){
			if ($find['type'] != 3){
				$find['value'] = '';
			}
			if ($data['value']) {
				if (!$data['value'] = $this->uploadImg($data['value'], $find['value'] ? $find['value'] : '')) {
					$this->error = '图片保存失败';
					return false;
				}
			}
		}
		return true;
	}

	/**
	 * @return array
	 * @author Colin <amcolin@126.com>
	 * @date 2021-12-21 下午5:49
	 */
	protected function onFind() {
		$find = $this->getFind();
		if ($find && $find['type'] == 3){
			$find['value'] = get_image($find['value']);
		}
		return [
			'find' => $find ,
			'types' => $this->getSelectOptions($this->model::TypesFormat , $find ? $find['type'] : '') ,
		];
	}

	/**
	 * 删除后
	 * @param bool $status
	 * @param array $find
	 * @return bool
	 */
	protected function onDeleteAfter($status, $find = []){
		if ($find['type'] == 3){
			$path = ltrim($find['image'] , '/');
			if (is_file($path)){
				unlink($path);
			}
		}
		return true;
	}
}